# -*- coding:utf-8 -*-

from sklearn.datasets import load_iris,load_boston
from sklearn.feature_selection import VarianceThreshold
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.linear_model import LinearRegression,SGDRegressor,Ridge
from sklearn.metrics import mean_squared_error
import joblib
import pandas as pd
import numpy as np
import sys
import pypinyin

sys.path.append("../")
from frameworks.utils.PadasExcelUtil import *
import re
import nums_from_string
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.decomposition import PCA
from scipy.stats import pearsonr
from services.CodesService import *
import warnings
warnings.filterwarnings('ignore')

def main():
    # 1）获取数据
    codeService = CodeService();
    data = codeService.getKlineDay();

    df = pd.DataFrame(data)
    print("特征数量：\n", df.shape)

    """
    # 2、实例化一个转换器类
    transfer = VarianceThreshold(threshold=10)

    data = df.iloc[:,:]

    print("data:\n", data)

    # 3、调用fit_transform
    data_new = transfer.fit_transform(data)
    print("data_new:\n", data_new, data_new.shape)

    # 计算某两个变量之间的相关系数
    r1 = pearsonr(data["最高"], data["最低"])
    print("radio与earn之间的相关性：\n", r1)
    """

    df['zf'] = df.apply(lambda row: float(((row["close"]-row["pre_close"])*100)/row["close"]), axis = 1)
    df['code'] = df.apply(lambda row: row['code'].replace("SH", "").replace("SZ",""), axis=1)

    newdf = df[['exchange',"all_money"]]

    # 2）划分数据集
    x_train, x_test, y_train, y_test = train_test_split(newdf, df["zf"], random_state=22)

    # 3）
    # 假设 X_train 是你的训练数据
    # 数据标准化
    scaler = StandardScaler()
    x_train = scaler.fit_transform(x_train)

    # 数据归一化到[0,1]范围
    min_max_scaler = MinMaxScaler()
    x_train = min_max_scaler.fit_transform(x_train)

    # 4）预估器
    estimator = LinearRegression()
    estimator.fit(x_train, y_train)

    # 保存模型
    joblib.dump(estimator, "my_ridge_line.pkl")
    # 加载模型
    # estimator = joblib.load("my_ridge_line.pkl")

    # 5）得出模型
    print("梯度下降-权重系数为：\n", estimator.coef_)
    print("梯度下降-偏置为：\n", estimator.intercept_)

    # 6）模型评估
    y_predict = estimator.predict(x_test)
    print("预测房价：\n", y_predict)
    error = mean_squared_error(y_test, y_predict)
    print("梯度下降-均方误差为：\n", error)
    return None

if __name__ == "__main__":
    main()